﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;

namespace Jayden.Dll.InformationProvider.WorldBank
{
	public class CountryIndicatorTable
	{
		private List<string> m_Dates;
		private List<Country> m_Countries;
		private CountryIndicatorValue[,] m_Values;

		public CountryIndicatorTable(WorldBankDataProvider provider, List<CountryIndicatorValue> values)
		{
			List<Country> countries = new List<Country>();
			List<string> years = new List<string>();
			HashSet<string> iso = new HashSet<string>();
			HashSet<string> dates = new HashSet<string>();

			foreach (CountryIndicatorValue value in values)
			{
				if (!iso.Contains(value.CountryIsoCode))
				{
					Country country = provider.GetCountry(value.CountryIsoCode);
					countries.Add(country);
					iso.Add(value.CountryIsoCode);
				}
				if (!dates.Contains(value.Date))
				{
					years.Add(value.Date);
					dates.Add(value.Date);
				}
			}

			m_Countries = countries;
			m_Dates = years;
			m_Dates.Reverse();
			m_Values = new CountryIndicatorValue[m_Countries.Count, m_Dates.Count];

			foreach (CountryIndicatorValue value in values)
			{
				Country country = provider.GetCountry(value.CountryIsoCode);
				int indexCountry = countries.IndexOf(country);
				int indexDate = years.IndexOf(value.Date);
#if DEBUG
				if (m_Values[indexCountry, indexDate] != null)
					throw new Exception("already have value for " + value);
#endif
				m_Values[indexCountry, indexDate] = value;
			}

		}

		public void SaveTsv(string path)
		{
			StringBuilder builder = new StringBuilder();
			builder.Append('\t');
			for (int y = 0; y < m_Dates.Count; y++)
			{
				builder.Append('\t');
				builder.Append(m_Dates[y]);
			}
			builder.AppendLine();
			for (int c = 0; c < m_Countries.Count; c++)
			{
				builder.Append(m_Countries[c].IsoCode);
				builder.Append('\t');
				builder.Append(m_Countries[c].Name);
				for (int y = 0; y < m_Dates.Count; y++)
				{
					builder.Append('\t');
					if (m_Values[c, y] != null && m_Values[c, y].Value != null)
						builder.Append(double.Parse(m_Values[c, y].Value, CultureInfo.InvariantCulture));
				}
				builder.AppendLine();
			}
			File.WriteAllText(path, builder.ToString());
		}
	}
}
